﻿namespace Ocelot.Admin.Api.Application
{
    public class DictionaryService : IDictionaryService, ITransient
    {
        private readonly SqlSugarScopeProvider _sqlserverDB;
        public DictionaryService(ISqlSugarClient db)
        {
            _sqlserverDB = db.AsTenant().GetConnectionScope(DatabaseConfigIdConst.OcelotSettings);
        }

        #region 查询

        /// <summary>
        /// 分页查询字典信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<SqlSugarPagedList<Dictionary>> GetPageDictionaryAsync(BasePageRequest request)
        {
            return await _sqlserverDB.Queryable<Dictionary>().With(SqlWith.NoLock)
                .OrderByDescending(o => o.Id)
                .ToPagedListAsync(request.Current, request.PageSize);
        }

        /// <summary>
        /// 查询字典项信息
        /// </summary>
        /// <param name="dictionaryType"></param>
        /// <returns></returns>

        public async Task<List<BaseSelectDto<string>>> GetDictionaryItemAsync(string dictionaryType)
        {
            var dic = await _sqlserverDB.Queryable<Dictionary>().With(SqlWith.NoLock)
                .Includes(o => o.DictionaryItems)
                .FirstAsync(o => o.DictionaryType == dictionaryType);
            if (dic == null)
            {
                throw Oops.Bah("该字典未配置");
            }
            return dic.DictionaryItems.Where(o => o.Enabled).Select(o => new BaseSelectDto<string>()
            {
                Label = o.Key,
                Value = o.Value
            }).ToList();
        }

        #endregion
    }
}